/**
*
*/
<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>问题日志</el-breadcrumb-item>
    </el-breadcrumb>
    <NoPermission
      v-if="!authFilter(permissionObj, 'index')">
    </NoPermission>

    <div v-else>
      <!-- 搜索筛选 -->
      <el-form :inline="true" :model="formInline" class="mgt16">
        <el-form-item>
          <el-form-item prop="问题ID">
            <el-input size="small" v-model="formInline.id" placeholder="请输入问题ID" clearable></el-input>
          </el-form-item>
        </el-form-item>
        <el-form-item>
          <el-form-item prop="日志名称">
            <el-input size="small" v-model="formInline.fileName" placeholder="请输入日志名称" clearable></el-input>
          </el-form-item>
        </el-form-item>
        <el-form-item>
          <el-button size="small" type="primary" icon="el-icon-search" @click="search">搜索</el-button>
        </el-form-item>
      </el-form>
      <!--列表-->
      <div class="relative">
        <table-top
          :showCheck="false"
          :showResult="false"
          :refCustom="refCustom"
          :sheetLast="sheetLast"
          :formInline="formInline"
          :exportExcelInfo="exportExcelInfo"
          :exportExcelArray="exportExcelArray"
          :exportExcelHead="exportExcelHead"
          :multipleSelection="multipleSelection"
          :exportExcelRequest="exportExcelRequest"
          :showSummary="showSummary"
          :summaryList="summaryList"
          :isSubtotal="isSubtotal"
          :mergeCells="mergeCells"
          :mergeName="mergeName"
          :showRedList="showRedList"
          :showGreenList="showGreenList"
          :showOrangeList="showOrangeList"
          :customColor="customColor"
          :customGreen="customGreen"
          :customOrange="customOrange"
          @onSuccess="onSuccess">
        </table-top>
        <div class="relative">
          <el-table
            :header-cell-style="{'font-weight': '600', 'color':'#333'}"
            size="small"
            :data="listData"
            highlight-current-row
            v-loading="loading"
            :height="tableHeight"
            :row-height="rowHeight"
            use-virtual
            border
            element-loading-text="拼命加载中"
            style="width: 100%;"
            :show-summary="showSummary"
            :summary-method="getSummaries"
            :span-method="objectSpanMethod"
            ref="multipleTable"
            @selection-change="handleSelectionChange">
            <el-table-column
              prop="selection"
              align="center"
              type="selection"
              width="60">
            </el-table-column>
            <el-table-column align="center" prop="id" label="问题ID" min-width="100px">
            </el-table-column>
            <el-table-column align="center" prop="createTime" label="上传时间" min-width="120px">
              <template slot-scope="scope">
                <div>{{scope.row.createTime|timestampToDay}}</div>
              </template>
            </el-table-column>
            <el-table-column align="center" prop="fileName" label="日志名称" min-width="180px">
            </el-table-column>
            <el-table-column align="center" prop="remark" label="描述" min-width="120px">
            </el-table-column>
            <el-table-column align="center" label="操作" fixed="right"
                             :min-width="operaWidth">
              <template slot-scope="scope"
                        v-if="listData&&listData.length>0">
                <el-button size="mini" type="primary" @click="downZip(scope.row.filePath)"
                           v-if="authFilter(permissionObj, 'download')">下载</el-button>
                <el-button size="mini" type="danger" @click="deleteColumn(scope.$index, scope.row)"
                           v-if="authFilter(permissionObj, 'delete')">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>

      </div>
      <!-- 分页组件 -->
      <Pagination v-bind:child-msg="pageparm" @callFather="callFather"></Pagination>
    </div>

  </div>
</template>

<script>
import Pagination from '../../components/Pagination'
// 输入建议
import AutoCompleteCustom from "@/components/AutoCompleteCustom.vue"
import TableTop from "@/components/table-top.vue"
import {mapGetters, mapState} from "vuex";
//上传excel
import UploadFile from "@/components/UploadFile.vue"
// 选择部门
// import config from "@/api/config.js";
// import * as dd from 'dingtalk-jsapi' // 此方式为整体加载，也可按需进行加载

import reportMin from "@/views/tatisticalReport/tatisticalReport.js"
export default {
  // 注册组件
  components: {
    Pagination,
    AutoCompleteCustom,
    TableTop,
    UploadFile
  },
  mixins:[reportMin],
  data() {
    return {
      loading: false, //是显示加载
      formInline: {
        page: 1,
        pagenum: 30,
        id: '',
        fileName: '',
      },
      listData: [], //用户数据
      // 分页参数
      pageparm: {
        currentPage: 1,
        pageSize: 30,
        total: 30
      },
      // 虚拟列表 start
      rowHeight: 40,
      tableHeight: window.innerHeight - 302,
      // tableHeight: document.documentElement.clientHeight - 254, // 表的高度
      // 虚拟列表 end
      // 导出表格start
      // 是否合并小格
      mergeCells: false,
      //合并表格名称
      mergeName: 'id',
      // 导出自定义字体颜色所属字段
      showRedList: ['是','未回答'],
      showGreenList: ['已回答'],
      showOrangeList: ['已查看'],
      // 导出自定义字体颜色
      customColor: 'D63640',
      customGreen: '1AD96F',
      customOrange: 'f2b400',
      // 是否小计
      isSubtotal: false,
      // 是否显示统计
      showSummary: false,
      // 统计字段列表
      summaryList: ['balance'],
      // 表格列最后一列，有边框样式，手动去掉
      sheetLast: '',
      // 导出数据接口
      exportExcelRequest:'problemlogList',
      //导出表格字段及formatter信息
      exportExcelArray: [
        {
          prop: 'id',
          label: '问题ID',
          formatterFlag: false,
          align: 'center',
        },
        {
          prop: 'createTime',
          label: '上传时间',
          formatterFlag: true,
          formatterType: 'time-type',
        },
        {
          prop: 'fileName',
          label: '日志名称',
          formatterFlag: false,
          align: 'center',
        },
        {
          prop: 'remark',
          label: '描述',
          formatterFlag: false,
          align: 'center',
        },
      ],
      // 导出excel表格宽高列表
      exportExcelHead:[
        { wpx: 100, wch: 20 },
        { wpx: 120, wch: 20 },
        { wpx: 180, wch: 20 },
        { wpx: 120, wch: 20 },
      ],
      //导出excel表格id及excel名称
      exportExcelInfo: {
        excelId: 'Lend',
        excelName: '问题日志列表记录.xlsx'
      },
      //需要导出的table的选择数据
      multipleSelection: [],
      refCustom: 'myChild'

    }
  },
  /**
   * 数据发生改变
   */

  /**
   * 创建完毕
   */
  created() {
    const vm = this
    vm.getData(this.formInline)
  },
  computed:{
    ...mapGetters(['userAuthList']),
    permissionObj(){
      if(this.userAuthList&&this.userAuthList.length>0){
        return this.authListFilter(this.userAuthList,'customManagement', 'problemLog')
      }
    },
    // 操作列表宽度
    operaWidth(){
      const vm = this
      const minWidth = 120
      const len = vm.authFilterLen(this.permissionObj, 'download', 'delete').length
      return len > 0 ? vm.multiply(len,90) : minWidth
    },
  },
  // 虚拟列表 start
  mounted() {
    /** 控制table的高度 */
    const vm = this
    // resize窗口节流
    window.addEventListener("resize", vm.throttleNew(vm.updateTableHeight, 300))
  },
  // vue设置列表高度自适应和show-summary的冲突
  updated() {
    const vm = this
    if(vm.showSummary){
      vm.$nextTick(()=>{
        vm.$refs['multipleTable'].doLayout()
      })
    }
  },
  beforeDestroy() {
    const vm = this
    window.removeEventListener('resize', vm.updateTableHeight)
  },
  // 虚拟列表 end

  /**
   * 里面的方法只有被调用才会执行
   */
  methods: {
    // 虚拟列表 start
    /**
     * 虚拟列表 更新表高
     */
    updateTableHeight() {
      const vm = this
      // console.log('vm.tableHeight', vm.tableHeight)
      const offsetHei = document.documentElement.clientHeight
      // const removeHeight = this.filterObj.length > 0 ? 285 : 254
      const removeHeight = 254
      vm.tableHeight = offsetHei - removeHeight
    },
    // 虚拟列表 end
    // 带输入建议
    handleSelect(item) {
      this.formInline.dept = item.value
    },
    // 测试携客云签名
    sortedObject(myObject) {
      // 使用Object.keys()获取对象键的数组
      // 使用sort()对数组进行排序
      // 使用map()结合Array.from()遍历键数组，返回一个新的对象
      return Array.from(
        Object.keys(myObject)
          .sort()
          .map(key => {
            return [key, myObject[key]];
          })
      ).reduce((obj, [key, value]) => {
        obj[key] = value;
        return obj;
      }, {});
    },
    getSign(){
      const vm = this

      let commonParam ={
        "appKey":"a62052c34c5f11a7bbf520eba7b8b52e",
        "version":"1.0",
        "ownerCompanyCode":"80624046",
        "operateCompanyCode":"80624046",
        "timestamps":"1715670910"
      }
      // (1) commonParam下的参数按照key字符串(除sign外)的字典序进行排序
      commonParam = this.sortedObject(commonParam);
      console.log("commonParam",commonParam);
      // (2) 按照key对应的value拼接字符串（非string类型也转化成string类型），中间用英文冒号(:)隔开
      let commonStr = Object.values(commonParam).map(val => {
        return [val];
      }).reduce((str, [value]) => {
        str += value + ':';
        return str;
      }, '');
      console.log("commonStr",commonStr);
      // (3) 在(2)得到的字符串后面追加 :appSecret
      const appKey = "b95d2efe1d924110e8d0a32e3fb0b7a0"
      commonStr+=appKey;
      console.log(":appSecret",commonStr);
      // (4) 对(3)得到的字符串进行MD5
      commonStr = this.$md5(commonStr)
      console.log("MD5",commonStr);
      // (5) 把(4)得到的字符串转换成小字
      commonStr = commonStr.toLowerCase()
      console.log("转换成小字",commonStr);
    },
    // 获取问题日志列表
    getData(parameter) {
      const vm = this
      // 测试携客云签名
      // vm.getSign();
      
      vm.loading = true

      /***
       * 调用接口，注释上面模拟数据 取消下面注释
       */
      vm.apiUrl[vm.exportExcelRequest](parameter,"POST")
        .then(res => {
          vm.loading = false
          const { data:{list=[],totalnum},code, msg } = res
          if (code != 0) {
            vm.showMessageMin({
              message: msg,
              type: 'error',
            })
          } else {
            // vm.listData = list
            // 合并小格
            vm.listData = vm.groupBy(list, vm.mergeName)
            // console.log('vm.listData', vm.listData)
            // 分页赋值
            vm.pageparm.currentPage = vm.formInline.page
            vm.pageparm.pageSize = vm.formInline.pagenum
            vm.pageparm.total = totalnum
          }
        })
        .catch(err => {
          if(err&&err.isCancel) return
          vm.loading = false
        })
    },
    // 分页插件事件
    callFather(parm) {
      const vm = this
      vm.formInline = {
        ...vm.formInline,
        page: parm.currentPage,
        pagenum: parm.pageSize
      }
      vm.getData(vm.formInline)
    },
    // 搜索事件
    search() {
      const vm = this
      vm.formInline = {
        ...vm.formInline,
        page: 1
      }
      vm.getData(vm.formInline)
    },
    // 删除
    deleteColumn(index, row) {
      const vm = this
      vm.$confirm('确定要删除吗?', '信息', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          vm.openFullScreen()
          const param = {
            id: row.id
          }
          vm.apiUrl.problemlogDelete(param,"POST")
            .then(res => {
              vm.closeFullScreen(vm.openFullScreen());
              const { code, msg } = res;
              if (code == 0) {
                vm.showMessageMin({
                  message: '已删除!',
                  type: 'success',
                })
                vm.getData(vm.formInline)
              } else {
                vm.showMessageMin({
                  message: msg,
                  type: 'error',
                })
              }
            })
        })
        .catch(() => {
          vm.showMessageMin({
            message: '已取消删除',
            type: 'info',
          })
        })
    },
    // 关闭编辑、增加弹出框
    closeDialog() {
      this.editFormVisible = false
    },

    //导出excel
    // 上传excel成功
    async onSuccess(data) {
      // console.log(data);
      const vm = this
      // 数据库的key为英文，我们上传的key为中文，需要一一转化
      const userRelations = Object.fromEntries(vm.exportExcelArray.map((item)=>{
        return [item.label,item.prop]
      }))
      console.log('obj', obj)
      // 将key值一一对应
      const newArr = data.results.map((item) => {
        let userInfo = {};
        Object.keys(item).forEach((key) => {
          if(userRelations[key]){
            userInfo[userRelations[key]] = item[key];
          }
          // userInfo[userRelations[key]] = item[key];
        });
        return userInfo;
      });

      // const newArr = data.results

      console.log(newArr);
      const param = {
        excelFrom: 'BillingPlan',
        excelList: newArr,
      }
      //   await importEmployee(param); // 调用上传接口
      vm.showMessageMin({
        message: '上传文件成功',
        type: 'success',
      })
      vm.isShow = false;
    },
    resetForm(formName) {
      const vm = this
      if(!vm.$refs[formName]) return
      vm.$refs[formName].resetFields();
      vm.$refs.UploadFile.clearFiles()
    },

  }
}
</script>

<style lang="less" scoped>

</style>
